package com.xiaoshi.forms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.xiaoshi.forms.dto.SysFormsDto;
import com.xiaoshi.forms.entity.SysForms;
import com.xiaoshi.forms.entity.SysFormsContent;
import com.xiaoshi.forms.entity.SysFormsField;
import com.xiaoshi.forms.mapper.SysFormsMapper;
import com.xiaoshi.forms.service.ISysFormsContentService;
import com.xiaoshi.forms.service.ISysFormsFieldService;
import com.xiaoshi.forms.service.ISysFormsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshi.interfaces.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 * 系统表单
 服务实现类
 * </p>
 *
 * @author yuankai
 * @since 2022-03-17
 */
@Service
@Slf4j
@Transactional
public class SysFormsServiceImpl extends ServiceImpl<SysFormsMapper, SysForms> implements ISysFormsService {

    @Autowired
    private ISysFormsFieldService formsFieldService;

    @Autowired
    private ISysFormsContentService formsContentService;

    @Override

    public boolean saveForms(SysFormsDto dto) {

        SysForms sysForms = new SysForms();
        BeanUtil.copyProperties(dto,sysForms);
        boolean save = this.save(sysForms);
        if(!save){
            return false;
        }

        LinkedHashMap hashMap = JSONUtil.toBean(dto.getJsonStr(), LinkedHashMap.class);
        Iterator<Map.Entry<String,String>> iter = hashMap.entrySet().iterator();
        while(iter.hasNext()){
            Map.Entry<String,String> entry = iter.next();
            String key = entry.getKey();

            SysFormsField sysFormsField = new SysFormsField();
            sysFormsField.setFieldName(key);
            sysFormsField.setFormId(sysForms.getId());
            boolean save1 = formsFieldService.save(sysFormsField);
            if(!save1){
                return false;
            }

            String value = entry.getValue();
            SysFormsContent content = new SysFormsContent();
            content.setContentText(value);
            content.setFieldId(sysFormsField.getFieldId());
            content.setFieldName(sysFormsField.getFieldName());
            content.setFormsId(sysForms.getId());
            content.setFormsName(sysForms.getName());
            boolean save2 = formsContentService.save(content);
            if(!save2){
                return false;
            }

            System.out.println(key+" "+value);
        }

        return true;
    }

    @Override
    public SysForms getDetailById(Long id) {
        return this.getById(id);
    }
}
